package com.gz.common;

import com.gz.common.model.*;
import com.gz.utils.TimeUtil;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import java.lang.System;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by gongzhen on 2018/6/2.
 */
public class OrderService {
	private static OrderService service;

	private OrderService() {
	}

	public static OrderService getService() {
		if (service == null) {
			service = new OrderService();
		}
		return service;
	}

	public String createOrderSN() {
		// 当前系统时间戳精确到毫秒
		Long simple = System.currentTimeMillis();
		// 三位随机数
		int random = new Random().nextInt(900) + 100;// 为变量赋随机值100-999;
		return "E" + TimeUtil.date2Str0(new Date()) + random;
	}

	public Order getOrder(int id) {
		Order order = Order.dao.findById(id);
		order.put("orderProductList", getOrderProductList(order.getId()));
		order.put("youhuis", order.getYouhuis());
		return order;
	}

	/**
	 * @param pageNum
	 * @param pageSize
	 * @param order_status
	 * @param userId
	 * @param payment_status
	 * @param shipping_status
	 * @param active
	 * @return
	 */
	public Page<Order> getOrder(int pageNum, int pageSize, Integer order_status, Integer userId, Integer payment_status,
			Integer shipping_status, boolean active) {
		String conditionSql = " active=false";
		if (userId != null) {
			conditionSql += " and userId=" + userId;
		}
		if (order_status != null) {
			conditionSql += " and order_status=" + order_status;
		}
		if (payment_status != null) {
			conditionSql += " and payment_status=" + payment_status;
		}
		if (shipping_status != null) {
			conditionSql += " and shipping_status=" + shipping_status;
		}
		if (shipping_status != null) {
			conditionSql += " and shipping_status=" + shipping_status;
		}
		Page<Order> orderPage = Order.dao.paginate(pageNum, pageSize, "select * ",
				"from tb_order where " + conditionSql + " order by createTime desc");
		for (Order order : orderPage.getList()) {
			order.put("orderProductList", getOrderProductList(order.getId()));
			order.put("youhuis", order.getYouhuis());
		}
		return orderPage;
	}

	/**
	 *
	 * @param orderId
	 * @return
	 */
	public List<OrderProduct> getOrderProductList(int orderId) {
		List<OrderProduct> orderProductList = OrderProduct.dao.find("SELECT * from tb_order_product where order_id=?",
				orderId);
		for (OrderProduct orderProduct : orderProductList) {
			orderProduct.put("product_img_temp", Constant.FILE_PATH + orderProduct.getProductImg());
		}
		return orderProductList;
	}

	/**
	 *
	 * @param orderId
	 * @return
	 */
	public OrderProduct getOrderProduct(int orderId) {
		OrderProduct orderProductList = OrderProduct.dao.findFirst("SELECT * from tb_order_product where order_id=?",
				orderId);
		return orderProductList;
	}

	public Address getAddress(String provinceName, String cityName, String countyName) {
		Region region = Region.dao.findFirst(
				"SELECT * from tb_region where type=3 and name=? and pid=(SELECT id from tb_region where type=2 and name=? and pid = (SELECT id from tb_region where type=1 and name=?))",
				countyName, cityName, provinceName);
		if (region == null) {
			return null;
		}
		Address address = new Address();
		address.setProvinceName(provinceName);
		address.setCityName(cityName);
		address.setCountyName(countyName);
		address.setCode(region.getCode());
		address.setPostFee(region.getPostFee());
		return address;
	}

	public Pay getPayByOrderId(Integer orderId) {
		Pay pay = Pay.dao.findFirst("select * from tb_pay where order_id=?", orderId);
		return pay;
	}

	public Pay createPay(Order order) {
		Pay pay = new Pay();
		pay.setOrderId(order.getId());
		pay.setPayMoney(Math.round(order.getPayFee() * 100));
		pay.setPayTime(new Date());
		pay.setTradeNo(order.getOrderSN());
		pay.save();
		return pay;
	}

	public void updatePayStatus(String out_trade_no, String transaction_id, Date time_end) {
		Pay pay = Pay.dao.findFirst("select * from tb_pay where trade_no=?", out_trade_no);
		pay.setPayTime(time_end);
		pay.setStatus(1);
		pay.setTransactionId(transaction_id);
		pay.update();
	}

	/**
	 * @author YinChile 查询销量排行榜
	 */
	public List<Order> findorOrderll() {
		List<Order> orderList = Order.dao.find("select pr.id,count(*),op.`name`,op.price,us.username\n"
				+ "from tb_order_product as op,tb_product as pr,tb_user as us\n"
				+ "where op.product_id=pr.id and us.id = pr.createuser\n" + "GROUP BY product_id\n"
				+ "ORDER BY count(*) desc");
		return orderList;
	}

	public Order findOrderByid(Integer orderid) {
		return Order.dao.findById(orderid);
	}

	/**
	 * 统计退货中待处理的订单
	 * 
	 * @return
	 */
	public List<Order> CountOutProuctOrder() {
		return Order.dao.find("SELECT COUNT(*) count  FROM tb_order where shipping_status=3");
	}

	/**
	 * 计算没发货订单
	 * 
	 * @return
	 */
	public List<Order> CountProuctNotdelivery() {
		return Order.dao.find("SELECT COUNT(*) count FROM tb_order where shipping_status=0");
	}

	/**
	 * 计算商品总销量
	 */
	public List<Product> SumProductSales() {
		return Product.dao.find("select SUM(sales) sum from tb_product");
	}

	/**
	 * 查询已付款的订单条数
	 * 
	 * @param userId 用户id
	 * @return
	 */
	public List<Order> CountPaymentOrders(Integer userId) {
		return Order.dao.find(
				"select count(*) count from tb_user u,tb_order o where u.id=o.userId and u.usergrade=3 and o.order_status in (2,3,4) and o.userId=?",
				userId);
	}

	/**
	 * 查询已付款的订单
	 * 
	 * @param pageNum  当前页
	 * @param pageSize 显示条数
	 */
	public Page<Order> PaymentOrders(int pageNum, int pageSize, Integer userId) {
		return Order.dao.paginate(pageNum, pageSize, "select o.* ",
				"from tb_user u,tb_order o where u.id=o.userId and u.usergrade=3 and o.order_status in (2,3,4) and o.userId=?",
				userId);
	}

	/**
	 * 确认收货
	 */
	public int confirmReceipt(Integer orderid, Integer userid) {
		return Db.update("update tb_order set order_status=4 where `id`=? and `userId`=? and order_status=3", orderid,
				userid);
	}

}
